﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Xml;
using WFDAL;
using System.IO;
using System.Collections;

namespace WFENGINE
{
    //引擎入口
    public class EngineEntry
    {
        public string _RegionXmlParam;
        public EngineParam _EngineParam;
        public OracleCommand ocm = new OracleCommand();
        /// <summary>
        /// 對外開放的入口
        /// </summary>
        /// <param name="xmlParam"></param>
        /// <returns></returns>
        /*
             <Params>
                <applyid></applyid>
                <signrecordid></signrecordid>
                <prcstepid></prcstepid>
                <userid>為空時，Engine自己獲取（排程或win程式執行時沒有用戶ID Cookie）</userid>
                <signtype>1自己2代理3授權</signtype>
                <priority>急件註記</priority>
                <memo><![CDATA[簽核提示（不顯示在單據內容裡）]]></memo>
                <userip>為空，由Engine自己獲取</userip>
                <usermac>為空，由Engine自己獲取</usermac>
                <execresult>1簽核3取回4退簽0作廢，-1跳過自己</execresult>
                <otheruserid>會簽/轉呈/覆核/轉交 人員</otheruserid>
                <stepname>新增簽核點名稱</stepname>
                <backsignstepid>退回簽核點ID</backsignstepid>
                <result>執行結果</result>
                <memoapply><![CDATA[簽核備註（顯示在單據內容裡）]]></memoapply>
                <ext_string nm="其他擴展信息"><![CDATA[預留]]></ext_string>
            </Params>
             */
        public string SignEntry(string xmlParam)
        {
            _EngineParam = new EngineParam();
            this._RegionXmlParam = xmlParam;//其他地方或可以使用
            _EngineParam = Xml2Param(xmlParam);
            switch (_EngineParam._EXECRESULT)
            {
                case "1":
                    this.SignApprove(_EngineParam);
                    break;
                case "3"://取回
                    this.SignGetBack(_EngineParam);
                    break;
                case "4"://退回
                    this.SignBack(_EngineParam);
                    break;
                case "0":
                    this.SignBack(_EngineParam);
                    break;
                default:
                    break;
            }
            return "";
        }

        private EngineParam Xml2Param(string xmlParam)
        {
            XmlTextReader xtr = new XmlTextReader(new StringReader(xmlParam));
            XmlDocument xd = new XmlDocument();
            xd.LoadXml(xmlParam);
            _EngineParam._APPLYID = xd.SelectSingleNode("Params/applyid").InnerText;
            _EngineParam._SIGNRECORDID = xd.SelectSingleNode("Params/signrecordid").InnerText;
            _EngineParam._PRCSTEPID = xd.SelectSingleNode("Params/prcstepid").InnerText;
            _EngineParam._USERID = xd.SelectSingleNode("Params/userid").InnerText;
            _EngineParam._SIGNTYPE = xd.SelectSingleNode("Params/signtype").InnerText;
            _EngineParam._PRIORITY = xd.SelectSingleNode("Params/priority").InnerText;
            _EngineParam._MEMO = xd.SelectSingleNode("Params/memo").InnerText;
            _EngineParam._USERIP = xd.SelectSingleNode("Params/userip").InnerText;
            _EngineParam._USERMAC = xd.SelectSingleNode("Params/usermac").InnerText;
            _EngineParam._EXECRESULT = xd.SelectSingleNode("Params/execresult").InnerText;
            _EngineParam._OTHERUSERID = xd.SelectSingleNode("Params/otheruserid").InnerText;
            _EngineParam._STEPNAME = xd.SelectSingleNode("Params/stepname").InnerText;
            _EngineParam._BACKSIGNSTEPID = xd.SelectSingleNode("Params/backsignstepid").InnerText;
            _EngineParam._RESULT = xd.SelectSingleNode("Params/result").InnerText;
            _EngineParam._MEMOAPPLY = xd.SelectSingleNode("Params/memoapply").InnerText;
            _EngineParam._EXT_STRING = xd.SelectSingleNode("Params/ext_string").InnerText;
            return _EngineParam;
        }

        #region 各种签核方法
        //簽核
        private string SignApprove(EngineParam param)
        {
            ocm.ExecuteSQL(string.Format(EngineSql.PRO_ENGINE_SIGNAPPROVE,
                param._SIGNRECORDID,
                param._APPLYID,
                param._PRCSTEPID,
                param._USERID,
                param._SIGNTYPE,
                "",
                "",
                param._MEMO,
                "",
                "",
                param._OTHERUSERID,
                param._BACKSIGNSTEPID,
                param._STEPNAME));
            return "Y";
        }
        //取回 & 結案後取回
        private string SignGetBack(EngineParam param)
        {
            return "Y";
        }
        //退簽
        private string SignBack(EngineParam param)
        {
            return "Y";
        }
        //轉呈、覆核、會簽、轉移(自己不签核，改为同级别人员签核)
        private string SignSpecial(EngineParam param)
        {
            return "Y";
        }
        //跳過（棄權）
        private string SignIgnore(EngineParam param)
        {
            return "Y";
        }
        #endregion

        #region Send Notice Mail
        /// <summary>
        /// Mail通知处理，采用模板处理
        /// </summary>
        /// <param name="okApplyIds">成功的单据ID</param>
        /// <param name="actionCode">签核动作代码</param>
        private bool SendNoticeMail(string okApplyIds, string actionCode)
        {
            #region HTML 模板

            /**
             <table style="border: solid 0px #98B2D7; width: 643px;" cellspacing="0" cellpadding="0">
    <tr>
        <td>
            <table style="border: 1px solid #65C3D6; font-size: 14px;" cellspacing="0" cellpadding="0" width="100%">
                <tr>
                    <td>
                        <img src="$Url$" />
                        <table cellspacing="0" cellpadding="0" border="0" width="100%">
                            <tr>
                                <td style="height: 25px; padding-left: 14px; color: #5E5E5E; font-family: 宋体; font-size: 16px;">
                                    尊敬的女士/先生，您好！您有如下信息(<font color="blue">$MessageType$</font>)
                                </td>
                            </tr>
                            <tr>
                                <td style="color: #666; padding-top: 5px; padding-left: 8px; font-size: 14px;">
                                    <div style="width: 98%; background-color: #FAF1BE; color: #000; position: relative;
                                        margin: 5px 5px 5px 5px">
                                        $Content$
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td style="color: #999; padding-top: 5px; padding-left: 14px; font-size: 14px;">
                                    请点击<a href="$SysUrl$">$SysName$</a>进入网站查看和签核!
                                </td>
                            </tr>
                            <tr>
                                <td style="color: #999; font-size: 12px; display: block; padding-top: 18px; padding-left: 14px;">
                                    本邮件是系统发出的邮件，请勿直接回复。<br />
                                    $SysName$ $SendDate$
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>
             * */
            #endregion
            try
            {
                //DataTable dt = this.DBEngine.GetAllMail(okApplyIds, actionCode);
                string configPath = System.Configuration.ConfigurationManager.AppSettings["APPdfPath"].ToString() + "template\\ewfmail.htm";
                string tempHtml = "";//WFBASE.WFFILE.LoadFileContent(configPath); //邮件内容
                string MailItemContent = "";
                /*string webUrl = System.Configuration.ConfigurationManager.AppSettings["SiteURL"].ToString() +
                    System.Configuration.ConfigurationManager.AppSettings["ApplicationName"].ToString();
                string _Url = webUrl + "/img/mail_title.gif";
                string _SysUrl = webUrl + "/login.aspx";
                string _MessageType = dt.Rows[0]["title"].ToString();
                string _Content = tempHtml;
                string _SysName = System.Configuration.ConfigurationManager.AppSettings["ApplicationCNName"].ToString();
                string _SendDate = System.DateTime.Now.ToString("yyyy-MM-dd");
                string p_Url = "", p_Lang = _Lang;

                if (dt.Rows.Count > 0)
                {
                    string strMail = dt.Rows[0]["mail"].ToString();
                    string strfold = dt.Rows[0]["fold"].ToString();

                    string strTestSite = "";
                    if (System.Configuration.ConfigurationManager.AppSettings["IsTestSite"] != null)//是否测试站台，Y是，N否
                        if (System.Configuration.ConfigurationManager.AppSettings["IsTestSite"].ToString().Trim() == "Y")
                            strTestSite = "<span style=\"font-Size:12pt;color:red\">" + Trans("此信息来自测试网站", p_Lang, "") + "！</span><br>";

                    string MgrMail = "", CCMail = "";
                    if (System.Configuration.ConfigurationManager.AppSettings["WebMasterMail"] != null)
                        MgrMail = System.Configuration.ConfigurationManager.AppSettings["WebMasterMail"].ToString();


                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["title"].ToString() != _MessageType || dt.Rows[i]["mail"].ToString() != strMail)
                        {
                            _Content = _Content.Replace("$MessageType$", _MessageType);
                            _Content = _Content.Replace("$SysName$", _SysName).Replace("$SysName$", _SysName);
                            _Content = _Content.Replace("$SendDate$", _SendDate);
                            _Content = _Content.Replace("$Url$", _Url);
                            _Content = _Content.Replace("$SysUrl$", _SysUrl);
                            MailItemContent = "<div style=\"width: 98%; background-color: #FAF1BE; color: #000; position: relative;margin: 5px 5px 5px 5px\">" +
                                MailItemContent + "</div>";
                            _Content = _Content.Replace("$Content$", MailItemContent);

                            new SendMailV3().SendMail(MgrMail, RecheckMail(strMail), CCMail, "EWF-" + _MessageType, _Content);

                            _MessageType = dt.Rows[i]["title"].ToString();
                            strMail = dt.Rows[i]["mail"].ToString();

                            MailItemContent = "";
                            _Content = tempHtml;
                        }

                        MailItemContent += "<ul style=\"list-style-type: none; line-height: 27px; font-weight: bolder;\">" +
                                                    "<li>" + Trans("文件类别", p_Lang, p_Url) + "：<font color=\"blue\">" + dt.Rows[i]["fact_no"].ToString() + "-" + dt.Rows[i]["processname"].ToString() + "</font></li>" +
                                                    "<li>" + Trans("单据代号", p_Lang, p_Url) + "：<font color=\"blue\">" + dt.Rows[i]["key2"].ToString() + "</font></li>" +
                                                    "<li>" + Trans("文件主旨", p_Lang, p_Url) + "：<font color=\"blue\">" + dt.Rows[i]["lkey"].ToString() + "</font></li>" +
                                                    "<li>" + Trans("讯息类别", p_Lang, p_Url) + "：<font color=\"blue\">" + dt.Rows[i]["title"].ToString() + "</font></li>" +
                                                "</ul>";
                    }

                    MailItemContent = "<div style=\"width: 98%; background-color: #FAF1BE; color: #000; position: relative;margin: 5px 5px 5px 5px\">" +
                        MailItemContent + "</div>";

                   _Content = _Content.Replace("$MessageType$", _MessageType);
                    _Content = _Content.Replace("$SysName$", _SysName).Replace("$SysName$", _SysName);
                    _Content = _Content.Replace("$SendDate$", _SendDate);
                    _Content = _Content.Replace("$Url$", _Url);
                    _Content = _Content.Replace("$SysUrl$", _SysUrl);
                    MailItemContent = "<div style=\"width: 98%; background-color: #FAF1BE; color: #000; position: relative;margin: 5px 5px 5px 5px\">" +
                        MailItemContent + "</div>";
                    _Content = _Content.Replace("$Content$", MailItemContent);

                    new SendMailV3().SendMail(MgrMail, RecheckMail(strMail), CCMail, "EWF-" + _MessageType, _Content);
                
                }*/
                return true;
            }
            catch (Exception ex)
            {
                new WFBASE.SendMail().SendSysReport("engine sendmail error:" + ex.ToString());
                return false;

            }
        }
        #endregion
        #region 执行签核动作
        /// <summary>
        /// 
        /// </summary>
        /// <param name="param"></param>
        /// <param name="bofOrEof">触发时机，B/E,签核之前或签核之后</param>
        /// <returns></returns>
        private string ExecuteAction(EngineParam param, string bofOrEof)
        {
            return "N";
        }

        /// <summary>
        /// 执行数据库后端程式
        /// </summary>
        /// <param name="param"></param>
        /// <param name="actionDB"></param>
        /// <returns></returns>
        private string ExecuteDbProcedure(EngineParam param, DataTable actionDB)
        {
            return "N";
        }
        /// <summary>
        /// 执行提供的可二次开发动作的Web Service
        /// </summary>
        /// <param name="param"></param>
        /// <param name="actionDB"></param>
        /// <returns></returns>
        private string ExecuteWS(EngineParam param, DataTable actionDB)
        {
            return "N";
        }
        #endregion

        #region 取得基本資料
        public DataTable GetApply(string applyId)
        {
            return null;
        }

        public DataTable GetCurSignRecord(string signRecordId)
        {
            return null;
        }
        //取得單據簽核歷程（不含取回/退回等過程中的歷程），只包含有效的歷程
        public DataTable GetSignRecords(string applyId)
        {
            return null;
        }
        //取得單據所有歷程
        public DataTable GetSignRecordsAll(string applyId)
        {
            return null;
        }
        //取得單據設置的動作（結案/作廢/結案後取回）
        //FormAction Union SignRecord Action，Action map to EngineParam.execAction
        //Action為簽核時，需處理檢查單據是否結案，若單據結案，需取得FormAction；否則取得SignRecord Action
        //Action為作廢/結案後取回時，直接使用FromAction。
        //No Action返回null，否則返回Action Info，含Action Property
        public DataTable GetAction(string signrecordId, string action)
        {
            return null;
        }


        #endregion
    }
}
